<template>
  <div className="schedule-container">
    <a-card className="schedule-card" title="规培麻醉医师轮转安排计划表">
      <!-- 查询条件 -->
      <div class="query-container">
        <a-form class="smart-query-form" :model="queryParams">
          <a-row class="smart-query-form-row" >
            <a-form-item label="学生等级" name="stuLevel" class="smart-query-form-item" required>
              <DictSelect key-code="STU_LEVEL" v-model:value="queryParams.stuLevel" width="200px" :allowClear="false" />
            </a-form-item>
            <a-form-item class="smart-query-form-item">
              <a-button-group>
                <a-button type="primary" @click="onSearch">
                  <template #icon>
                    <ReloadOutlined />
                  </template>
                  查询
                </a-button>
                <a-button @click="resetQuery">
                  <template #icon>
                    <SearchOutlined />
                  </template>
                  重置
                </a-button>
              </a-button-group>
            </a-form-item>
          </a-row>
        </a-form>
      </div>
      <div className="table-container">
        <a-table
            :dataSource="scheduleData"
            :columns="scheduleColumns"
            :pagination="false"
            :rowClassName="(record, index) => (index % 2 === 0 ? 'table-row-light' : 'table-row-dark')"
            bordered
        />
      </div>
    </a-card>
  </div>
</template>

<script setup>
import {ref, onMounted, computed, watch} from 'vue';
import dayjs from 'dayjs';
import {studentScheduleApi} from '../../api/schedule/schedule-api';
import {dictApi} from '../../api/support/dict-api';
import DictSelect from "/@/components/support/dict-select/index.vue";
import { employeeApi } from '/@/api/system/employee-api';
import {encryptData} from "/@/lib/encrypt.js";

const scheduleData = ref([]);
const students = ref([]);

// 添加查询参数
const queryParams = ref({
  stuLevel: undefined,
  pageNum : 1,
});

// 重置查询条件
function resetQuery() {
  
}

// 监听学生等级变化，自动查询
watch(() => queryParams.value.stuLevel, (newVal, oldVal) => {
  if (newVal) {
    fetchScheduleData();
  }
});

// 搜索
function onSearch() {
  fetchScheduleData();
}

// 获取并处理数据
const generateDateRange = (startYear) => {
  const result = [];
  let year = Number(startYear);
  let month = 9;
  for (let i = 0; i < 36; i++) {
    if (month > 12) {
      year++;
      month = 1;
    }
    result.push(`${year}.${month.toString().padStart(2, '0')}`);
    month++;
  }
  return result;
};

const fetchStudents = async () => {

  const res = await employeeApi.listEmployee({ roleId: 60, stuLevel: queryParams.value.stuLevel[0] });
  if (res.code === 0 && Array.isArray(res.data)) {
    students.value = res.data.map(item => ({
      studentId: item.employeeId,
      studentName: item.actualName
    }));
  } else {
    students.value = [];
  }
};

const fetchScheduleData = async () => {
  try {
    const stuLevelYear = queryParams.value.stuLevel;
    if (!stuLevelYear) {
      scheduleData.value = [];
      return;
    }
    await fetchStudents();
    const dateRange = generateDateRange(stuLevelYear);
    // 计算起止时间
    const startMonth = dateRange[0];
    const endMonth = dateRange[dateRange.length - 1];
    const startTime = dayjs(startMonth.replace('.', '-') + '-01').startOf('month').format('YYYY-MM-DD HH:mm:ss');
    const endTime = dayjs(endMonth.replace('.', '-') + '-01').endOf('month').format('YYYY-MM-DD HH:mm:ss');
    // 查询所有学生的排班信息
    const response = await studentScheduleApi.getList({encryptData:encryptData({ startTime, endTime })});
    if (response.code === 0 && response.data) {
      const monthlyData = new Map();
      dateRange.forEach(monthKey => {
        const row = { date: monthKey };
        students.value.forEach(stu => {
          row[stu.studentId] = '';
        });
        monthlyData.set(monthKey, row);
      });
      response.data.forEach(item => {
        const monthKey = dayjs(item.startTime).format('YYYY.MM');
        const studentId = item.studentId || item.employeeId;
        if (monthlyData.has(monthKey) && studentId) {
          monthlyData.get(monthKey)[studentId] = item.deptName;
        }
      });
      scheduleData.value = Array.from(monthlyData.values());
    }
  } catch (error) {
    console.error('获取数据失败:', error);
  }
};

// 生成表格列定义
// 添加科室选项数据
const deptOptions = ref([]);

// 获取科室字典数据
const getDeptOptions = async () => {
  try {
    const response = await dictApi.valueList('SCHEDULE_DEPT');
    if (response.code === 0) {
      deptOptions.value = response.data.map(item => ({
        label: item.valueName,
        value: item.valueCode
      }));
    }
  } catch (error) {
    console.error('获取科室列表失败:', error);
  }
};

// 处理科室修改
const handleDeptChange = async (value, record, studentId,studentName) => {
  try {
    const params = {};
    // 获取最新数据以确保更新正确的记录
    const response = await studentScheduleApi.getList(    {encryptData:encryptData(params)});
    if (response.code === 0 && response.data && response.data) {
      // 查找对应的记录
      const targetRecord = response.data.find(item =>
          dayjs(item.startTime).format('YYYY.MM') === record.date &&
          item.studentName === studentName && item.studentId === studentId
      );

      // 获取选中的科室名称
      const selectedDept = deptOptions.value.find(opt => opt.value === value);

      if (targetRecord) {
        // 更新已存在的记录
        const updateResponse = await studentScheduleApi.update({encryptData:encryptData({
            id: targetRecord.id,
            deptId: value,
            deptName: selectedDept.label
          })});

        if (updateResponse.code === 0) {
          // 更新成功后刷新数据
          fetchScheduleData();
        }
      } else {
        // 如果没有找到记录，则新增排班
        const [year, month] = record.date.split('.');
        const startDate = dayjs(`${year}-${month}-01`).startOf('day');
        const endDate = startDate.endOf('month').endOf('day');

        console.log("stu:"+studentId);
        const addResponse = await studentScheduleApi.add({encryptData:encryptData({
            studentId: studentId,
            studentName: studentName,
            deptId: value,
            deptName: selectedDept.label,
            startTime: startDate.format('YYYY-MM-DD HH:mm:ss'),
            endTime: endDate.format('YYYY-MM-DD HH:mm:ss')
          })});

        if (addResponse.code === 0) {
          // 新增成功后刷新数据
          fetchScheduleData();
        }
      }
    } else {
      console.error('获取数据失败: 返回数据格式不正确');
    }
  } catch (error) {
    console.error('更新/新增科室失败:', error);
  }
};

// 修改表格列定义中的单元格渲染方式
const scheduleColumns = computed(() => [
  {
    title: '日期',
    dataIndex: 'date',
    key: 'date',
    width: '120px',
    fixed: 'left',
    align: 'center'
  },
  ...students.value.map(student => ({
    title: student.studentName,
    dataIndex: student.studentId,
    key: student.studentId,
    align: 'center',
    customCell: (record) => ({
      onDblclick: (event) => {
        const cell = event.target;
        const currentDeptName = record[student.studentId]; // 这里要用studentId作为key
        const select = document.createElement('select');
        select.style.width = '100%';
        select.style.height = '32px';

        // 添加空选项
        const emptyOption = document.createElement('option');
        emptyOption.value = '';
        emptyOption.text = '请选择';
        select.appendChild(emptyOption);

        // 添加所有科室选项
        deptOptions.value.forEach(option => {
          const opt = document.createElement('option');
          opt.value = option.value;
          opt.text = option.label;
          // 如果是当前科室名称，则设置为选中
          if (option.label === currentDeptName) {
            opt.selected = true;
          }
          select.appendChild(opt);
        });

        select.onchange = (e) => {
          const selectedValue = e.target.value;
          if (!selectedValue) return; // 如果选择了空选项，不做任何操作

          const selectedText = e.target.options[e.target.selectedIndex].text;
          handleDeptChange(selectedValue, record,student.studentId, student.studentName);
          cell.textContent = selectedText;
        };

        // 添加失去焦点事件处理
        select.onblur = () => {
          // 恢复原始内容
          cell.textContent = currentDeptName || '';
        };

        cell.textContent = '';
        cell.appendChild(select);
        select.focus();
      }
    })
  }))
]);

onMounted(() => {
  // 假设有学生等级字典数据，可以这样赋默认值
  if (!queryParams.value.stuLevel) {
    queryParams.value.stuLevel = ['2025']; // 或实际第一个字典项的valueCode
  }
  getDeptOptions();
  fetchScheduleData();
});
</script>

<style scoped>
.schedule-container {
  /* padding: 6px; */
  background: #f0f2f5;
  min-height: 100vh;
}

.schedule-card {
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.schedule-card:hover {
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.table-container {
  margin-top: 6px;
}

:deep(.ant-card) {
  background: #fff;
}

:deep(.ant-card-head) {
  border-bottom: 2px solid #2f54eb;
  padding: 16px 24px;
}

:deep(.ant-card-head-title) {
  font-weight: 600;
  font-size: 18px;
  color: #2f54eb;
}

:deep(.ant-table) {
  background: #fff;
  border-radius: 8px;
}

:deep(.ant-table-thead > tr > th) {
  background: #f0f5ff;
  color: #2f54eb;
  font-weight: 600;
  padding: 16px;
  border-bottom: 2px solid #d9e3ff;
}

:deep(.table-row-light) {
  background: #fff;
}

:deep(.table-row-dark) {
  background: #f8faff;
}

:deep(.ant-table-tbody > tr > td) {
  padding: 16px;
  transition: all 0.3s;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background: #e6f7ff !important;
}

/* 响应式优化 */
@media screen and (max-width: 768px) {
  .schedule-container {
    padding: 12px;
  }

  :deep(.ant-card-head-title) {
    font-size: 16px;
  }

  :deep(.ant-table-thead > tr > th),
  :deep(.ant-table-tbody > tr > td) {
    padding: 12px 8px;
    font-size: 14px;
  }
}
</style>
